library(tidyverse)
library(haven)
library(stargazer) # "markwestcott34/stargazer-booktabs"
library(starpolishr)
library(ggsignif)
library(fixest)
library(showtext)
library(weights)
library(anesrake)
library(multcomp)

palette = c('#808080', '#bb0a1e', '#006400','#bb0a1e', '#006400')
tablenotes = rjson::fromJSON(file='code/table-notes.json')
controls_description = "Controls include age, age squared, a set of race indicators, a Hispanic indicator, a male indicator, and a set of education indicators."
robust_description = 'Robust standard errors are reported.'
p_description = '*, **, and *** denote statistical significance at the 10\\%, 5\\%, and 1\\% levels, respectively.'
tablenotes = map_chr(tablenotes, str_interp)

theme_excuses <- function () { 
  theme_bw(base_size=12, base_family="LM Roman 10") %+replace% 
    theme(
      axis.title.x = element_blank()
    )
}
theme_excuses = list(theme_bw(base_size=16, base_family="LM Roman 10"),
                     theme(axis.title.x = element_blank(),
                           axis.title.y = element_text(size=22),
                           axis.text = element_text(size=22)),
                     scale_fill_manual(values=palette),
                     scale_color_manual(values=palette),
                     guides(fill=F,col=F))

two_palette = list(scale_fill_manual(values=palette[2:3]),
                   scale_color_manual(values=palette[2:3]))

four_palette = list(scale_fill_manual(values=palette[2:5]),
                   scale_color_manual(values=palette[2:5]))

reg = function(formula, data, type='ols', ...) {
  form = as.formula(str_interp(formula))
  if (type == 'ols') {
    model = feols(form, data=data, ...)
  } else if (type == 'logit')
    model = feglm(form, data=data, family = binomial(link = 'logit'), ...)
  args = list(...)
  if (!is.null(args$weights)) {
    data$w = data[[as.character(terms(args$weights)[[2]])]]
  } else {
    data$w = 1
  }
  dv = as.character(terms(form)[[2]])
  mean = mean(data[[dv]]) %>% round(3) %>%  format(nsmall = 3)
  list(model, mean)
}



output = function(models, notes, label, ...) {
  tex = modelsummary(map(models, 1),
                     stars = T,
                     gof_omit = 'Adj|Within|AIC|BIC|Log|Pseudo',
                     output = 'latex',
                     escape = F,
                     ...) 
  tex = str_split(tex, '\\n')[[1]]
  nmodels = length(models)
  col_labels = paste(paste0('(', 1:nmodels, ')'), collapse=' & ')
  
  tex[which(str_detect(tex, 'Model 1'))] = paste0('&', col_labels, ' \\\\')
  tex = tex[!(substring(tex, 1, 3)=='FE:')]
  tex = str_replace(tex, 'tab:', str_interp('tab:${label}'))
  tex = tex[!(substring(tex, 1, 11)=='Std. errors')]
  tex = str_replace(tex, 'Num\\.Obs\\.', 'Observations')
  tex = str_replace(tex, 'R2', 'R-squared')
  
  str_replace_all(tex, '\\)\\\\\\\\', '\\)\\\\\\\\ \\\\addlinespace')
  
  obs_row = which(str_detect(tex,'Observations'))
  
  tex = c(
    tex[1:6],
    tex[9:(obs_row-1)],
    tex[(obs_row+2):(which(tex=='\\bottomrule')-1)],
    '\\addlinespace',
    tex[(obs_row):(obs_row+1)],
    paste0(paste(c('Dep.~var.~mean', map(models, 2)), collapse =' & '), '\\\\'),
    paste0(paste(c('Dep.~var.~std.~dev.', map(models, 3)), collapse=' & '), '\\\\'),
    '\\bottomrule \\end{tabular}',
    '\\begin{tablenotes} \\footnotesize',
    paste0('\\item \\textit{Notes:} ', str_interp(notes)),
    '\\end{tablenotes}',
    '\\end{table}')
  
  return(tex)
}


get_p = function(subset) {
  model1 = lm(posted~excuse, data=subset)
  pvalues = summary(model1)$coefficients[,'Pr(>|t|)']
  p_excuse_noexcuse = p_format(pvalues['excuse'])
  return(p_excuse_noexcuse)
}


p_format = function(p) {
  
  if (p<0.001) {
    pformat = format.pval(p, digits=3, eps = 0.001)
  }
  
  if (p>=0.001 & p<0.01) {
    pformat = sprintf('%.3f', p)
  }
  else if (p>=0.01 & p < 0.1) {
    pformat = sprintf('%.3f', p)
  }
  else if (p>=0.1) {
    pformat = sprintf('%.2f', p)
  }
  
  return(pformat)
}


create_summary = function(outcome) {
  get_p = function(subset) {
    model1 = lm(outcome~excuse, data=subset)
    pvalues = summary(model1)$coefficients[,'Pr(>|t|)']
    p_excuse_noexcuse = p_format(pvalues['excuse'])
    p_excuse_noexcuse
  }
  
  data$outcome = data[[outcome]]
  
  hc_p = get_p(data %>% filter(exp=='defund'))
  lc_p = get_p(data %>% filter(exp=='notcredible'))
  exp4_p = get_p(data %>% filter(exp=='deport'))
  
  means = data %>% 
    group_by(expgroup, condition) %>% 
    summarise(mean = mean(outcome, na.rm=T),
              se = sd(outcome, na.rm=T)/sqrt(n()))
  
  return(list(means, hc_p, lc_p, exp4_p))
}



data_finalize = function(data) {
  
  data = data %>% mutate(condition = case_when(
    excuse==1 ~ 'Rationale',
    noexcuse==1 ~ 'No rationale',
  ),
  condition = recode(condition, 'Rationale'='Cover', 'No rationale'='No Cover'),
  condition = factor(condition, levels = c('No Cover','Cover')),
  partisan_num = partisan,
  partisan = case_when(
    partisan==-2 ~ 'Very liberal',
    partisan==-1 ~ 'Liberal',
    partisan==0 ~ 'Neither liberal nor conservative',
    partisan==1 ~ 'Conservative',
    partisan==2 ~ 'Very conservative'
  ),
  partisan = factor(partisan, levels=c('Very conservative','Conservative','Neither liberal nor conservative','Liberal','Very liberal')),
  education = ifelse(education %in% c('Professional degree (JD, MD)', 'Doctoral degree', "Master's degree"), 'Post-bachelor degree', education),
  education = factor(education, levels = c('Less than high school degree', 
                                           'High school graduate (high school diploma or equivalent including GED)',
                                           'Some college but no degree',
                                           'Associate degree in college (2-year)',
                                           "Bachelor's degree in college (4-year)",
                                           'Post-bachelor degree')),
  race = ifelse(race == 'Native American, Inuit or Aleut' | race == 'Native Hawaiian/Pacific Islander', 'Other', race),
  race = factor(race, levels = c('Other', 'African American/Black', 'Asian/Asian American', 'Caucasian/White')),
  black = ifelse(is.na(race), NA,
                 ifelse(race == 'African American/Black', 1, 0)),
  asian = ifelse(is.na(race), NA,
                 ifelse(race == 'Asian/Asian American', 1, 0)),
  agesq = age^2,
  hs = ifelse(is.na(education), NA,
                           ifelse(education != 'Less than high school degree', 1, 0)),
  bachelors = ifelse(is.na(education), NA,
                         ifelse(education %in% c('Bachelor\'s degree in college (4-year)', 'Post-bachelor degree'), 1, 0)))
  
  return(data)
}


data_finalize_persuasion = function(data) {
  
  data = data %>% mutate(condition = case_when(
    info==1 ~ 'Provided article',
    info==0 ~ 'Not provided article',
  ),
  condition = factor(condition, levels = c('Not provided article','Provided article')),
  partisan_num = partisan,
  partisan = case_when(
    partisan==-2 ~ 'Very liberal',
    partisan==-1 ~ 'Liberal',
    partisan==0 ~ 'Neither liberal nor conservative',
    partisan==1 ~ 'Conservative',
    partisan==2 ~ 'Very conservative'
  ),
  partisan = factor(partisan, levels=c('Very conservative','Conservative','Neither liberal nor conservative','Liberal','Very liberal')),
  education = ifelse(education %in% c('Professional degree (JD, MD, MBA)', 'Doctoral degree', "Master's degree"), 'Post-bachelor degree', education),
  education = factor(education, levels = c('Some high school',
                                           'High school degree/GED',
                                           'Some college',
                                           '2-year college degree',
                                           "4-year college degree",
                                           'Post-bachelor degree')),
  race = ifelse(race == 'Native American, Inuit or Aleut' | race == 'Native Hawaiian/Pacific Islander', 'Other', race),
  race = factor(race, levels = c('Other', 'African American/Black', 'Asian/Asian American', 'Caucasian/White')),
  black = ifelse(is.na(race), NA,
                 ifelse(race == 'African American/Black', 1, 0)),
  asian = ifelse(is.na(race), NA,
                 ifelse(race == 'Asian/Asian American', 1, 0)),
  agesq = age^2,
  hs = ifelse(is.na(education), NA,
                           ifelse(education != 'Some high school', 1, 0)),
  bachelors = ifelse(is.na(education), NA,
                         ifelse(education %in% c('4-year college degree', 'Post-bachelor degree'), 1, 0)))
  
  return(data)
  
}


data_finalize_motive = function(data) {
  
  data = data %>% mutate(information = str_detect(handcoding, 'information'),
         persuasion = str_detect(handcoding, 'persuasion'),
         rationale = str_detect(handcoding, 'rationale'),
         choose_rationale = post=='Tweet B',
         excuse = condition=='excuse',
         condition = recode(condition, 'excuse'='Cover', 'noexcuse'='No Cover'),
         condition = factor(condition, levels = c('No Cover','Cover')),
         excuse = case_when(condition=='Cover' ~ 1,
                            condition=='No Cover' ~ 0),
         noexcuse = 1-excuse) %>%
    mutate(education = ifelse(education %in% c('Professional degree (JD, MD)', 'Doctoral degree', "Master's degree"), 'Post-bachelor degree', education),
           education = factor(education, levels = c('Less than high school degree', 
                                                    'High school graduate (high school diploma or equivalent including GED)',
                                                    'Some college but no degree',
                                                    'Associate degree in college (2-year)',
                                                    "Bachelor's degree in college (4-year)",
                                                    'Post-bachelor degree')),
           race = ifelse(race == 'Native American, Inuit or Aleut' | race == 'Native Hawaiian/Pacific Islander', 'Other', race),
           race = factor(race, levels = c('Other', 'African American/Black', 'Asian/Asian American', 'Caucasian/White')),
           black = ifelse(is.na(race), NA,
                          ifelse(race == 'African American/Black', 1, 0)),
           asian = ifelse(is.na(race), NA,
                          ifelse(race == 'Asian/Asian American', 1, 0)),
           agesq = age^2,
           hs = ifelse(is.na(education), NA,
                       ifelse(education != 'Less than high school degree', 1, 0)),
           bachelors = ifelse(is.na(education), NA,
                              ifelse(education %in% c('Bachelor\'s degree in college (4-year)', 'Post-bachelor degree'), 1, 0)),
           partisan_num = partisan,
           partisan = as.factor(partisan))
  
}









make_represent_sender = function(data, type) {
  
  data = data %>% 
    dplyr::select(posted, credibility, education, race, attrit, excuse, noexcuse, age, age2, hisp, male, white, black, asian, hs, bachelors, exp) %>%
    bind_rows(pew)
  
  if (type == 'defund') {
    data = data %>%
      # Dems/Inds
      filter((exp == 'defund' & !is.na(posted)) | (political_party %in% c(2,3) & exp == 'pew'))
    group = c('defund' = 'Defund', 'pew' = 'Pew (Inds and Dems)')
    title = 'Experiment 1: Sample representativeness'
    label = 'defund-sender-representativeness'
  } 
  else if (type == 'defund-replication') {
    data = data %>%
      # Dems
      filter((exp == 'defund-replication' & !is.na(posted)) | (political_party == 2 & exp == 'pew'))
    group = c('defund' = 'Defund', 'pew' = 'Pew (Dems)')
    title = 'Experiment 1R: Sample representativeness'
    label = 'defund-sender-replication-representativeness'
  }
  else if (type == 'rainforest') {
    data = data %>%
      # Dems/Inds/Reps
      filter((exp == 'rainforest' & !is.na(posted))| (!is.na(political_party) & exp == 'pew'))
    group = c('rainforest' = 'Placebo', 'pew' = 'Pew (Inds, Dems and Reps)')
    title = 'Auxiliary Experiment 2: Sample representativeness'
    label = 'rainforest-sender-representativeness'
  } 
  else if (type == 'dst') {
    data = data %>%
      # Dems/Reps
      filter((exp == 'dst' & !is.na(posted))| (political_party %in% c(1,2) & exp == 'pew'))
    group = c('dst' = 'Placebo', 'pew' = 'Pew (Dems and Reps)')
    title = 'Auxiliary Experiment 3: Sample representativeness'
    label = 'dst-sender-representativeness'
  } 
  else if (type == 'deport') {
    data = data %>% 
      # Inds/Reps
      filter((exp == 'deport' & !is.na(posted))| (political_party %in% c(1,3) & exp == 'pew'))
    group = c('deport' = 'Deport', 'pew' = 'Pew (Inds and Reps)')
    title = 'Experiment 3: Sample representativeness'
    label = 'deport-sender-representativeness'
  } else if (type == 'defund-hypo') {
    temp = data %>% filter(exp == 'defund-hypo')
    data = data %>%
      # Dems/Inds
      filter((exp == 'defund-hypo' & !is.na(posted)) | (political_party %in% c(2,3) & exp == 'pew'))
    group = c('defund-hypo' = 'Defund', 'pew' = 'Pew (Inds and Dems)')
    title = 'Auxiliary Experiment 6: Sample representativeness'
    if (temp$credibility[1]=='credible') {
      label = 'defund-hypo-hc-representativeness'
    } else if (temp$credibility[1]=='notcredible') {
      label = 'defund-hypo-lc-representativeness'
    }
  }
  make_row = function(outcome) {
    dict = c('age'='Age', 
             'black'='Black', 
             'white'='White', 
             'asian'='Asian', 
             'hisp'='Hispanic', 
             'male'='Male',
             'hs' = 'High school diploma', 
             'bachelors' = 'Bachelors degree or higher')
    data$outcome = data[[outcome]]
    
    values = c(mean(data$outcome[data$exp==type], na.rm=T), weighted.mean(data$outcome[data$exp=='pew'], w = data$weight[data$exp=='pew'], na.rm=T))
    values = c(dict[outcome], map_chr(values, function(x) formatC(x, digits=2, format='f')))
    values = paste(values, collapse = ' & ')
    values = paste(values, '\\\\')
    
    
    return(values)
  }
  
  rows = purrr::map(c('age','black','white','asian','hisp','male',
                      'hs', 'bachelors'), make_row)
  
  rows = c(rows[1], '\\addlinespace', rows[2:5], '\\addlinespace', rows[6], '\\addlinespace', rows[7:8])
  
  head = c('\\begin{tabular}{lcc}',
           '\\toprule',
           paste(paste(c('', group[[1]], group[[2]]), collapse = ' & '), '\\\\'),
           '\\cmidrule(lr){2-2} \\cmidrule(lr){3-3}') 
  
  out = c('\\begin{table}[H]',
          '\\centering', 
          str_interp('\\caption{${title}}'), 
          str_interp('\\label{t:${label}}'),
          '\\vspace*{2mm}',
          '\\begin{threeparttable}',
          head,
          '',
          unlist(rows), 
          '\\bottomrule',
          '\\end{tabular}',
          '\\begin{tablenotes} \\footnotesize',
          '\\item \\textit{Notes:} ',
          tablenotes[['full-represent']],
          '\\end{tablenotes}',
          '\\end{threeparttable}',
          '\\end{table}')
  
  writeLines(out, str_interp('output/tables/${label}.tex'))
  
}




make_represent_receiver = function(data, type) {
  
  data = data %>% 
    dplyr::select(education, race, attrit, excuse, noexcuse, age, age2, hisp, male, white, black, asian, hs, bachelors, exp) %>%
    bind_rows(pew)

  if (type == 'defund') {
    data = data %>%
      # Dems/Inds
      filter((exp == 'defund') | (political_party %in% c(2,3) & exp == 'pew'))
    group = c('defund' = 'Defund', 'pew' = 'Pew (Inds and Dems)')
    title = 'Experiment 2: Sample representativeness'
    label = 'defund-receiver-representativeness'
  } else if (type == 'notcredible') {
    data = data %>%
      # Dems/Inds
      filter((exp == 'notcredible')| (political_party %in% c(2,3) & exp == 'pew'))
    group = c('nocredible' = 'Placebo', 'pew' = 'Pew (Inds and Dems)')
    title = 'Auxiliary Experiment 7: Sample representativeness'
    label = 'defund-receiver-lc-representativeness'
  } else if (type == 'deport') {
    data = data %>% 
      # Dems/Inds
      filter((exp == 'deport')| (political_party %in% c(2,3) & exp == 'pew'))
    group = c('deport' = 'Deport', 'pew' = 'Pew (Inds and Dems)')
    title = 'Experiment 4: Sample representativeness'
    label = 'deport-receiver-representativeness'
  }
  
  make_row = function(outcome) {
    dict = c('age'='Age', 
             'black'='Black', 
             'white'='White', 
             'asian'='Asian', 
             'hisp'='Hispanic', 
             'male'='Male',
             'hs' = 'High school diploma', 
             'bachelors' = 'Bachelors degree or higher')
    data$outcome = data[[outcome]]
    
    
    values = c(mean(data$outcome[data$exp==type], na.rm=T), weighted.mean(data$outcome[data$exp=='pew'], w = data$weight[data$exp=='pew'], na.rm=T))
    
    values = c(dict[outcome], map_chr(values, function(x) formatC(x, digits=2, format='f')))
    values = paste(values, collapse = ' & ')
    values = paste(values, '\\\\')
    
    
    return(values)
  }
  
  rows = purrr::map(c('age','black','white','asian','hisp','male',
                      'hs', 'bachelors'), make_row)
  
  rows = c(rows[1], '\\addlinespace', rows[2:5], '\\addlinespace', rows[6], '\\addlinespace', rows[7:8])
  
  head = c('\\begin{tabular}{lcc}',
           '\\toprule',
           paste(paste(c('', group[[1]], group[[2]]), collapse = ' & '), '\\\\'),
           '\\cmidrule(lr){2-2} \\cmidrule(lr){3-3}') 
  
  out = c('\\begin{table}[H]',
          '\\centering', 
          str_interp('\\caption{${title}}'), 
          str_interp('\\label{t:${label}}'),
          '\\vspace*{2mm}',
          '\\begin{threeparttable}',
          head,
          '',
          unlist(rows), 
          '\\bottomrule',
          '\\end{tabular}',
          '\\begin{tablenotes} \\footnotesize',
          '\\item \\textit{Notes:} ',
          tablenotes[['full-represent']],
          '\\end{tablenotes}',
          '\\end{threeparttable}',
          '\\end{table}')
  
  writeLines(out, str_interp('output/tables/${label}.tex'))
  
}



make_represent_other = function(data, type) {
  
  data = data %>% 
    bind_rows(pew)
  
  if (type == 'anticipated') {
    data = data %>% 
      # Dems/Inds
      filter((exp == 'anticipated') | (political_party %in% c(2,3) & exp == 'pew'))
    group = c('anticipated' = 'Anticipated persuasion', 'pew' = 'Pew (Inds and Dems)')
    title = 'Auxiliary Experiment 4: Sample representativeness'
    label = 'anticipated-persuasion-representativeness'
  } else if (type == 'motive') {
    data = data %>% 
      # Dems/Inds
      filter((exp == 'motive') | (political_party %in% c(2,3) & exp == 'pew'))
    group = c('motive' = 'Motives', 'pew' = 'Pew (Inds and Dems)')
    title = 'Auxiliary Experiment 5: Sample representativeness'
    label = 'motives-representativeness'
  } else if (type == 'sanction') {
    data = data %>%
      # Dems/Inds/Reps
      filter((exp == 'sanction') | (!is.na(political_party) & exp == 'pew'))
    group = c('defund' = 'Defund', 'pew' = 'Pew (Inds, Dems and Reps)')
    title = 'Auxiliary Survey: Sample representativeness'
    label = 'sanction-representativeness'
  } else if (type == 'purs-defund') {
    data = data %>%
      # Dems/Inds
      filter((exp == 'purs-defund') | (political_party %in% c(2,3) & exp == 'pew')) 
    group = c('purs-defund' = 'Defund', 'pew' = 'Pew (Inds and Dems)')
    title = 'Auxiliary Experiment 1: Sample representativeness'
    label = 'defund-persuasion-representativeness'
  } else if (type == 'purs-deport') {
    data = data %>%
      # Reps/Inds
      filter((exp == 'purs-deport')| (political_party %in% c(1,3) & exp == 'pew'))
    group = c('purs-defund' = 'Deport', 'pew' = 'Pew (Inds and Reps)')
    title = 'Auxiliary Experiment 8: Sample representativeness'
    label = 'deport-persuasion-representativeness'
  }
  
  make_row = function(outcome) {
    dict = c('age'='Age', 
             'black'='Black', 
             'white'='White', 
             'asian'='Asian', 
             'hisp'='Hispanic', 
             'male'='Male',
             'hs' = 'High school diploma', 
             'bachelors' = 'Bachelors degree or higher')
    data$outcome = data[[outcome]]
    
    
    values = c(mean(data$outcome[data$exp==type], na.rm=T), weighted.mean(data$outcome[data$exp=='pew'], w = data$weight[data$exp=='pew'], na.rm=T))
    
    values = c(dict[outcome], map_chr(values, function(x) formatC(x, digits=2, format='f')))
    values = paste(values, collapse = ' & ')
    values = paste(values, '\\\\')
    
    return(values)
  }
  
  rows = purrr::map(c('age','black','white','asian','hisp','male',
                      'hs', 'bachelors'), make_row)
  
  rows = c(rows[1], '\\addlinespace', rows[2:5], '\\addlinespace', rows[6], '\\addlinespace', rows[7:8])
  
  
  head = c('\\begin{tabular}{lcc}',
           '\\toprule',
           paste(paste(c('', group[[1]], group[[2]]), collapse = ' & '), '\\\\'),
           '\\cmidrule(lr){2-2} \\cmidrule(lr){3-3}') 
  
  out = c('\\begin{table}[H]',
          '\\centering', 
          str_interp('\\caption{${title}}'), 
          str_interp('\\label{t:${label}}'),
          '\\vspace*{2mm}',
          '\\begin{threeparttable}',
          head,
          '',
          unlist(rows), 
          '\\bottomrule',
          '\\end{tabular}',
          '\\begin{tablenotes} \\footnotesize',
          '\\item \\textit{Notes:} ',
          tablenotes[['full-represent']],
          '\\end{tablenotes}',
          '\\end{threeparttable}',
          '\\end{table}')
  
  writeLines(out, str_interp('output/tables/${label}.tex'))
  
}





make_balance_sender = function(data) {
  
  data = data %>% filter(!is.na(posted))
  
  if (data$exp[1] == 'deport') {
    title = 'Experiment 3: Balance of covariates'
    label = 'deport-sender-balance'
    data$nind = (data$ind == 0)
    dic_list = c('age'='Age', 'agesq'='Age squared', 'black'='Black', 
                 'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
                 'hs' = 'High school diploma', 'bachelors' = 'Bachelors degree',
                 'ind' = 'Independent', 'partisan_num'='Ideology')
    map_list = c('age','black','asian','white','hisp','male', 'hs','bachelors', 'ind','partisan_num')
  } 
  else if (data$exp[1] == 'defund') {
    title = 'Experiment 1: Balance of covariates'
    label = 'defund-sender-balance'
    data$nind = (data$ind == 0)
    dic_list = c('age'='Age', 'agesq'='Age squared', 'black'='Black', 
                 'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
                 'hs' = 'High school diploma', 'bachelors' = 'Bachelors degree',
                 'ind' = 'Independent', 'partisan_num'='Ideology')
    map_list = c('age','black','asian','white','hisp','male', 'hs','bachelors', 'ind','partisan_num')
  } 
  else if (data$exp[1] == 'defund-replication') {
    title = 'Experiment 1R: Balance of covariates'
    label = 'defund-sender-replication-balance'
    dic_list = c('age'='Age', 'agesq'='Age squared', 'black'='Black', 
                 'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
                 'hs' = 'High school diploma', 'bachelors' = 'Bachelors degree',
                 'partisan_num'='Ideology')
    map_list = c('age','black','asian','white','hisp','male', 'hs','bachelors', 'partisan_num')
  }
  else if (data$exp[1] == 'rainforest') {
    title = 'Auxiliary Experiment 2: Balance of covariates'
    label = 'rainforest-sender-balance'
    data$rep = (data$party == 'Republican')
    data$dem = (data$party == 'Democrat')
    dic_list = c('age'='Age', 'agesq'='Age squared', 'black'='Black', 
                 'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
                 'hs' = 'High school diploma', 'bachelors' = 'Bachelors degree',
                 'ind' = 'Independent', 'rep' = 'Republican', 'dem' = 'Democrat', 'partisan_num'='Ideology')
    map_list = c('age','black','asian','white','hisp','male', 'hs','bachelors', 'ind', 'rep', 'dem', 'partisan_num')
  } 
  else if (data$exp[1] == 'dst') {
    title = 'Auxiliary Experiment 3: Balance of covariates'
    label = 'dst-sender-balance'
    data$dem = (data$party == 'Democrat')
    dic_list = c('age'='Age', 'agesq'='Age squared', 'black'='Black', 
                 'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
                 'hs' = 'High school diploma', 'bachelors' = 'Bachelors degree',
                 'ind' = 'Independent', 'dem' = 'Democrat', 'partisan_num'='Ideology')
    map_list = c('age','black','asian','white','hisp','male', 'hs','bachelors', 'dem', 'partisan_num')
  } 
  else if (data$exp[1] == 'defund-hypo' & data$credibility[1] == 'credible') {
    title = 'Auxiliary Experiment 6: Balance of covariates'
    label = 'defund-hypo-hc-balance'
    data$nind = (data$ind == 0)
    dic_list = c('age'='Age', 'agesq'='Age squared', 'black'='Black', 
                 'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
                 'hs' = 'High school diploma', 'bachelors' = 'Bachelors degree',
                 'ind' = 'Independent', 'partisan_num'='Ideology')
    map_list = c('age','black','asian','white','hisp','male', 'hs','bachelors', 'ind', 'partisan_num')
  } 
  else if (data$exp[1] == 'defund-hypo' & data$credibility[1] == 'notcredible') {
    title = 'Auxiliary Experiment 6: Balance of covariates'
    label = 'defund-hypo-lc-balance'
    data$nind = (data$ind == 0)
    dic_list = c('age'='Age', 'agesq'='Age squared', 'black'='Black', 
                 'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
                 'hs' = 'High school diploma', 'bachelors' = 'Bachelors degree',
                 'ind' = 'Independent', 'partisan_num'='Ideology')
    map_list = c('age','black','asian','white','hisp','male', 'hs','bachelors', 'ind', 'partisan_num')
  }
  
  make_row = function(outcome) {
    dict = dic_list
    data$outcome = data[[outcome]]
    model = lm(outcome~excuse, data=data)
    p1 = summary(model)$coefficients['excuse','Pr(>|t|)']
    values = c(mean(data$outcome, na.rm=T), sd(data$outcome, na.rm=T), mean(data$outcome[data$excuse==1], na.rm=T), 
               mean(data$outcome[data$noexcuse==1], na.rm=T), p1)
    values = c(dict[outcome], map_chr(values, function(x) formatC(x, digits=2, format='f')))
    values = paste(values, collapse = ' & ')
    values = paste(values, '\\\\')
    return(values)
  }
  
  rows = map(map_list, make_row)
  template = readLines('code/templates/exp1-balance-template.tex')
  rows = c(rows[1], '\\addlinespace', rows[2:5], '\\addlinespace', rows[6], '\\addlinespace', rows[7:8], '\\addlinespace', rows[9:length(rows)])
  out = c(template[1:2],
          str_interp('\\caption{${title}}'), 
          str_interp('\\label{t:${label}}'),
          template[5:12], unlist(rows), template[13:19])
  writeLines(out, str_interp('output/tables/${label}.tex'))
}




make_balance_receiver = function(data) {
  
  if (data$exp[1] == 'deport') {
    title = 'Experiment 4: Balance of covariates'
    label = 'deport-receiver-balance'
  } else if (data$exp[1] == 'defund') {
    title = 'Experiment 2: Balance of covariates'
    label = 'defund-receiver-balance'
  } else if (data$exp[1] == 'notcredible') {
    title = 'Auxiliary Experiment 7: Balance of covariates'
    label = 'defund-receiver-lc-balance'
  } 
  
  data$nind = (data$ind == 0)
  
  make_row = function(outcome) {
    dict = c('age'='Age', 'black'='Black', 
             'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
             'hs' = 'High school diploma', 
             'bachelors' = 'Bachelors degree',
             'ind' = 'Independent', 'partisan_num'='Ideology')
    data$outcome = data[[outcome]]
    model = lm(outcome~excuse, data=data)
    p1 = summary(model)$coefficients['excuse','Pr(>|t|)']
    values = c(mean(data$outcome, na.rm=T), sd(data$outcome, na.rm=T), mean(data$outcome[data$excuse==1], na.rm=T), 
               mean(data$outcome[data$noexcuse==1], na.rm=T), p1)
    values = c(dict[outcome], map_chr(values, function(x) formatC(x, digits=2, format='f')))
    values = paste(values, collapse = ' & ')
    values = paste(values, '\\\\')
    
    return(values)
  }
  
  rows = purrr::map(c('age','black','asian','white','hisp','male',
                      'hs','bachelors', 
                      'ind', 'partisan_num'), make_row)
  template = readLines('code/templates/exp1-balance-template.tex')
  rows = c(rows[1], '\\addlinespace', rows[2:5], '\\addlinespace', rows[6], '\\addlinespace', rows[7:8], '\\addlinespace', rows[9:10])
  
  out = c(template[1:2],
          str_interp('\\caption{${title}}'), 
          str_interp('\\label{t:${label}}'),
          template[5:12], unlist(rows), template[13:19])
  
  writeLines(out, str_interp('output/tables/${label}.tex'))
  
}


make_balance_other = function(data) {
  
  if (data$exp[1] == 'anticipated') {
    title = 'Auxiliary Experiment 4: Balance of covariates'
    label = 'anticipated-persuasion-balance'
  } else if (data$exp[1] == 'motive') {
    title = 'Auxiliary Experiment 5: Balance of covariates'
    label = 'motives-balance'
    
  } 

  data$nind = (data$ind == 0)
  
  make_row = function(outcome) {
    dict = c('age'='Age', 'black'='Black', 
             'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
             'hs' = 'High school diploma', 
             'bachelors' = 'Bachelors degree',
             'ind' = 'Independent', 'partisan_num'='Ideology')
    data$outcome = data[[outcome]]
    model = lm(outcome~excuse, data=data)
    p1 = summary(model)$coefficients['excuse','Pr(>|t|)']
    values = c(mean(data$outcome, na.rm=T), sd(data$outcome, na.rm=T), mean(data$outcome[data$excuse==1], na.rm=T), 
               mean(data$outcome[data$noexcuse==1], na.rm=T), p1)
    values = c(dict[outcome], map_chr(values, function(x) formatC(x, digits=2, format='f')))
    values = paste(values, collapse = ' & ')
    values = paste(values, '\\\\')
    return(values)
  }
  
  rows = purrr::map(c('age','black','asian','white','hisp','male',
                      'hs','bachelors','ind','partisan_num'), make_row)
  template = readLines('code/templates/exp1-balance-template.tex')
  rows = c(rows[1], '\\addlinespace', rows[2:5], '\\addlinespace', rows[6], '\\addlinespace', rows[7:8], '\\addlinespace', rows[9:10])
  
  out = c(template[1:2],
          str_interp('\\caption{${title}}'), 
          str_interp('\\label{t:${label}}'),
          template[5:12], unlist(rows), template[13:19])
  
  writeLines(out, str_interp('output/tables/${label}.tex'))
  
}



make_balance_persuasion = function(data) {
  
  if (data$exp[1] == 'purs-deport') {
    title = 'Auxiliary Experiment 8: Balance of covariates'
    label = 'deport-persuasion-balance'
  } 
  else if (data$exp[1] == 'purs-defund') {
    title = 'Auxiliary Experiment 1: Balance of covariates'
    label = 'defund-persuasion-balance'
  }
    data$nind = (data$ind == 0)
    dic_list = c('age'='Age', 'agesq'='Age squared', 'black'='Black', 
                 'white'='White', 'asian'='Asian', 'hisp'='Hispanic', 'male'='Male',
                 'hs' = 'High school diploma', 'bachelors' = 'Bachelors degree',
                 'ind' = 'Independent', 'partisan_num'='Ideology')
    map_list = c('age','black','asian','white','hisp','male', 'hs','bachelors',
                 'ind', 'partisan_num')
 
  make_row = function(outcome) {
    dict = dic_list
    data$outcome = data[[outcome]]
    model = lm(outcome~info, data=data)
    p1 = summary(model)$coefficients['info','Pr(>|t|)']
    values = c(mean(data$outcome, na.rm=T), sd(data$outcome, na.rm=T), mean(data$outcome[data$info==1], na.rm=T), 
               mean(data$outcome[data$info==0], na.rm=T), p1)
    values = c(dict[outcome], map_chr(values, function(x) formatC(x, digits=2, format='f')))
    values = paste(values, collapse = ' & ')
    values = paste(values, '\\\\')
    
    return(values)
  }
  
  rows = purrr::map(map_list, make_row)
  template = readLines('code/templates/exp2-balance-template.tex')
  rows = c(rows[1], '\\addlinespace', rows[2:5], '\\addlinespace', rows[6], '\\addlinespace', rows[7:8], '\\addlinespace', rows[9:10])
  
  out = c(template[1:2],
          str_interp('\\caption{${title}}'), 
          str_interp('\\label{t:${label}}'),
          template[5:12], unlist(rows), template[13:19])
  
  writeLines(out, str_interp('output/tables/${label}.tex'))
  
}



